<?php

namespace Frieza\Modules\McnUser\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\McnBackstageOriginatorPublishDetail;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class McnOutputController extends Controller
{
    const EXCEL_MAP = [
        ['pos' => 'A', 'title' => '内容生产周', 'key' => 'week_range'],
        ['pos' => 'B', 'title' => 'uid', 'key' => 'uid'],
        ['pos' => 'C', 'title' => '昵称', 'key' => 'nick'],
        ['pos' => 'D', 'title' => '创作者等级', 'key' => 'user_product_level'],
        ['pos' => 'E', 'title' => '所在社群', 'key' => 'association'],
        ['pos' => 'F', 'title' => '新增优质note数', 'key' => 'best_note'],
        ['pos' => 'G', 'title' => '新增精选note数', 'key' => 'good_note'],
        ['pos' => 'H', 'title' => '新增优质整屋数', 'key' => 'best_article'],
        ['pos' => 'I', 'title' => '新增精选整屋数', 'key' => 'good_article'],
        ['pos' => 'J', 'title' => '新增价值note数', 'key' => 'value_note'],
        ['pos' => 'K', 'title' => '新增价值整屋数', 'key' => 'value_article'],
        ['pos' => 'L', 'title' => '新增挂载wiki价值note数', 'key' => 'wiki_value_note'],
        ['pos' => 'M', 'title' => '价值note wiki挂载率', 'key' => 'value_note_wiki_rate'],
        ['pos' => 'N', 'title' => '新增挂圈子价值note数', 'key' => 'circle_value_note'],
        ['pos' => 'O', 'title' => '价值note圈子挂载率', 'key' => 'value_note_circle_rate'],
    ];

    public function index(Request $request, Content $content): Content
    {
        $page = $request->input("page", 1);
        $pageSize = $request->input("per_page", 30);

        $where = $search = self::getFilterInfo($request);
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize,];

        $dataArr = McnBackstageOriginatorPublishDetail::select('*', $where);
        $dataArr = self::formateData($dataArr);
        $total = McnBackstageOriginatorPublishDetail::count($search);

        $gridModel = new pGridDataModel($dataArr, $total, [
            'perPage' => $pageSize,
        ]);

        $gridList = Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $search) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableExport();
                $grid->disableActions();

                $grid->tools(function ($tools) use ($search) {
                    $export_url = http_build_query($search);
                    $url = url('/admin/mcnUser/output/export?' . $export_url);
                    $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="' . $url . '"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a></div>';
                    $tools->append($button);
                });

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->expand();

                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->between('time', '内容生产周')->date();
                        $filter->equal('uid', 'uid')->placeholder("请输入用户uid");
                        $filter->equal('association', '所在社群')->placeholder("所在社群");
                    });

                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('lvl', '创作者等级')->checkbox([
                            "Lv0" => "lv0",
                            "Lv1" => "lv1",
                            "Lv2" => "lv2",
                            "Lv3" => "lv3",
                            "Lv4" => "lv4",
                            "Lv5" => "lv5",
                            "Lv6" => "lv6",
                            "Lv7" => "lv7",
                        ]);
                        $filter->equal('nick', '昵称')->placeholder("请输入昵称");
                    });
                });

                $grid->column("week_range", "内容生产周");
                $grid->column('uid', 'uid');
                $grid->column('nick', '昵称');
                $grid->column('user_product_level', '创作者等级');
                $grid->column('association', '所在社群');
                $grid->column('best_note', '新增优质note数');
                $grid->column('good_note', '新增精选note数');
                $grid->column('best_article', '新增优质整屋数');
                $grid->column('good_article', '新增精选整屋数');
                $grid->column('value_note', '新增价值note数');
                $grid->column('value_article', '新增价值整屋数');
                $grid->column('wiki_value_note', '新增挂载wiki价值note数');
                $grid->column('value_note_wiki_rate', '价值note wiki挂载率');
                $grid->column('circle_value_note', '新增挂圈子价值note数');
                $grid->column('value_note_circle_rate', '价值note圈子挂载率');

                $grid->actions(function ($actions) {
                    $actions->disableDelete();
                    $actions->disableEdit();
                    $actions->disableView();
                });
            });

        return $content
            ->header("创作者生产明细")
            ->row($gridList);
    }

    public function export(Request $request)
    {
        $excelInfo = [
            [//sheet0数据
                'title' => '用户基础信息',
                'rowTitle' => self::EXCEL_MAP,
                'data' => [],
            ],
        ];

        $search = self::getFilterInfo($request);
        $dataArr = McnBackstageOriginatorPublishDetail::select('*', $search);
        $dataArr = self::formateData($dataArr);
        if (count($dataArr) == 0) {
            $error = new MessageBag([
                'title' => '没有数据',
            ]);
            return back()->with(compact('error'));
        }

        foreach ($dataArr as $row) {
            $rowValArr = [];
            foreach ($excelInfo[0]['rowTitle'] as $title) {
                $rowValArr[] = $row[$title['key']];
            }
            $excelInfo[0]['data'][] = $rowValArr;
        }

        $excelObj = new DownExcel();
        $excelObj->setFileName('product_detail');
        //设置列宽
        $widths = ['A' => 15, 'B' => 15, 'C' => 25, 'D' => 15, 'E' => 20, 'G' => 20, 'J' => 20];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');

        Log::debug("生产明细", compact('excelInfo'));
        $excelObj->createMultiSheet($excelInfo);
    }

    private static function formateData($dataArr)
    {
        $arr = [];
        foreach ($dataArr as $key => $value) {
            $num = $value['value_note_wiki_rate'] * 100;
            $value['value_note_wiki_rate'] = round($num, 2) . '%';

            $num = $value['value_note_circle_rate'] * 100;
            $value['value_note_circle_rate'] = round($num, 2) . '%';

            $arr[] = $value;
        }
        return $arr;
    }

    private static function getFilterInfo(Request $request): array
    {
        $week = [];
        $start = $end = 0;
        $time = $request->input('time');
        if (!empty($time['start'])) {
            $start = strtotime($time['start']);
            $week[] = date('Y-W', $start);
        }
        if (!empty($time['end'])) {
            $end = strtotime($time['end']);
            $week[] = date('Y-W', $end);
        }
        if ($end > $start) {
            for ($i = $start; $i < $end; $i += 3600 * 24) {
                $week[] = date('Y-W', $i);
            }
        }
        $week = array_unique($week);
        Log::debug("周周周", compact('week'));

        $uid = $request->input('uid', 0);
        $nick = $request->input('nick', '');
        $association = $request->input('association', '');
        $lvlArr = $request->input('lvl', []);

        $where = [];
        if ($uid) {
            $where['uid'] = $uid;
        }
        if ($nick) {
            $where['nick'] = $nick;
        }
        if ($association) {
            $where['association'] = $association;
        }
        if ($lvlArr) {
            $where['user_product_level'] = $lvlArr;
        }
        if ($week) {
            $where['week'] = $week;
        }

        Log::debug("search参数", $where);

        return $where;
    }
}
